package com.example.service.impl;

import com.example.service.ICircuitBreakerService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author ：liukai
 * @date ：Created in 2021/9/6 6:08 下午
 * @description：
 * @modified By：
 * @version: $
 */
@Service
@Slf4j
public class CircuitBreakerServiceImpl implements ICircuitBreakerService {

    @Override
    public String getUserOK(int id) {
        return "获取成功,id为：" + id;
    }

    @HystrixCommand(fallbackMethod = "getUserTimeOutFallBack", commandProperties = {
            // 超时之后执行 fallbackMethod
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
            // 超时之后是否中断
            @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
            // 最大并发请求超过3个，就会触发 fallbackMethod
            @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "3"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000")
    })
    @Override
    public String getUserTimeOut(int id) {
//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            log.info("id为" + id + "连接超时");
//            return "连接超时";
//        }
        log.info("id为" + id + "连接未超时");
        return "连接未超时";
    }

    public String getUserTimeOutFallBack(int id) {
        log.info("id为" + id + "连接超时");
        return "id为" + id + "连接超时";
    }

    @Override
    public String testCircuitBreaker(int id) {

        return null;
    }
}
